DimenCache

object DimenCache

EN Global, lock-free, shared cache for all AppDimens dimension calculations.

Thread Safety: Completely thread-safe. All reads and writes are lock-free using AtomicLongArray / AtomicIntegerArray. If two threads write identically-keyed entries simultaneously, the last write wins — always correct because both computed the same value.

PT Cache global, lock-free e compartilhado para todos os cálculos de dimensão do AppDimens.

Types

Link copied to clipboard
data class CacheStats(val capacity: Int, val populated: Int, val fillRatio: Float, val hits: Long = 0, val misses: Long = 0, val evictions: Long = 0, val hitRate: Float = 0.0f)

EN Cache usage statistics snapshot. The hits, misses, evictions, and hitRate fields are only meaningful when diagnosticsEnabled is true.

Link copied to clipboard

EN Calculation types based on the library's package structure. PT Tipos de cálculo baseados na estrutura de pacotes da biblioteca.

Link copied to clipboard
internal class ScreenFactors

EN Holds all screen-derived scaling factors in an object padded to exceed two ARM64 cache lines (2 × 64 bytes = 128 bytes), ensuring that writes during updateFactors do not invalidate unrelated reads on sibling CPU cores.

Link copied to clipboard
internal class ShardWrapper(shardSize: Int)

EN Padded cache shard wrapper that prevents false sharing between shards across CPU cores on ARM64 (cache line = 64 bytes).

Link copied to clipboard

EN Dimension type discriminator for the cache key. PT Discriminador de tipo de dimensão para a chave de cache.

Properties

Link copied to clipboard
private var _scope: CoroutineScope?
Link copied to clipboard
internal const val ADJUSTMENT_SCALE: Float
Link copied to clipboard
internal const val CACHE_SIZE: Int = 2048

Number of slots in the primary (Tier-1) fast cache. Must be a power of 2 so that key and MASK is a fast modulo.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
internal val Context.dataStore: ERROR CLASS: Symbol not found for DataStore<ERROR CLASS: Symbol not found for Preferences>
Link copied to clipboard

EN When true, hit/miss/eviction counters are incremented on every cache operation. Uses LongAdder for low-contention counting. Disabled by default so production apps pay zero overhead.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
internal const val INV_BASE_RATIO: Float = 0.0033333334f
Link copied to clipboard

EN Master switch for the cache system. If disabled, all calls will recompute. PT Chave mestre para o sistema de cache. Se desativado, todos os cálculos são refeitos.

Link copied to clipboard
Link copied to clipboard

Internal flag to avoid AtomicBoolean.get overhead on every hot-path call.

Link copied to clipboard
Link copied to clipboard
internal val KEY_CACHE_DATA: ERROR CLASS: Unresolved name: byteArrayPreferencesKey
Link copied to clipboard
internal val KEY_SW_DP: ERROR CLASS: Unresolved name: intPreferencesKey
Link copied to clipboard

EN Backward-compatible accessors — still referenced by DimenCacheTest. These are thin aliases into shards; no extra memory is allocated.

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard
private val saveFlow: MutableSharedFlow<Context>
Link copied to clipboard
internal val scope: CoroutineScope
Link copied to clipboard
private val scopeLock: Any
Link copied to clipboard
Link copied to clipboard
internal const val SHARD_COUNT: Int = 4

EN Cache Sharding (Concurrency Partitioning) Split the cache into 4 shards to reduce false sharing and bus contention.

Link copied to clipboard
internal const val SHARD_MASK: Int
Link copied to clipboard
internal const val SHARD_SIZE: Int
Link copied to clipboard
internal const val SHARD_SIZE_MASK: Int
Link copied to clipboard

EN Sharded, padded primitive cache storage. Replaces the previous keysArray / valueBitsArray pair. Each shard is wrapped in a ShardWrapper with 128-byte padding.

Link copied to clipboard

Functions

Link copied to clipboard
fun addResetListener(listener: () -> Unit)

EN Registers a listener to be notified when the cache is cleared. PT Registra um listener para ser notificado quando o cache for limpo.

Link copied to clipboard
internal fun buildKey(baseValue: Float, isLandscape: Boolean, ignoreMultiWindows: Boolean, calcType: DimenCache.CalcType, qualifier: DpQualifier, inverter: Inverter, applyAspectRatio: Boolean, valueType: DimenCache.ValueType, customSensitivityK: Float? = null): Long

Packs all dimension-calculation parameters into a single 64-bit Long key.

internal fun buildKey(baseValue: Int, isLandscape: Boolean, ignoreMultiWindows: Boolean, calcType: DimenCache.CalcType, qualifier: DpQualifier, inverter: Inverter, applyAspectRatio: Boolean, valueType: DimenCache.ValueType, customSensitivityK: Float? = null): Long
Link copied to clipboard
internal fun calculateRawScaling(baseValue: Float, applyAspectRatio: Boolean, customSensitivityK: Float?): Float

EN Unified high-performance scaling engine. Reads from factors — padded object, guaranteeing that the read of scale and arMultiplier land on the same cache line as all other factor fields.

Link copied to clipboard
fun clear(context: Context? = null)

EN Clears all cache slots. Java-compatible alias.

Link copied to clipboard
fun clearAll(context: Context? = null)

EN Clears all cache entries using AtomicLongArray.lazySet / AtomicIntegerArray.lazySet with 4× manual loop unrolling. This avoids issuing a full memory barrier on every element, which is safe because the next getOrPut will provide the required acquire/release semantics. Thread-safe.

Link copied to clipboard
fun getBatch(keys: LongArray, context: Context? = null, compute: (Int) -> Float): FloatArray

EN SIMD-friendly batch resolution.

Link copied to clipboard
Link copied to clipboard
inline fun getOrPut(key: Long, crossinline compute: () -> Float): Float

Backward compatibility for non-context calls.

inline fun getOrPut(key: Long, context: Context? = null, crossinline compute: () -> Float): Float

EN Reads from the cache or computes (and stores) a new value. Lock-free.

Link copied to clipboard
internal fun getOrPutAspectRatio(normalizedAr: Float, context: Context? = null): Float
Link copied to clipboard
internal fun getOrPutInternal(key: Long, context: Context?, compute: () -> Float): Float

EN Non-inline core logic for getOrPut. Separated so that the public inline function does not need access to internal fields of ShardWrapper directly. This function is @PublishedApi, making it visible to the inlined call-sites.

Link copied to clipboard
internal fun init(context: Context)
Link copied to clipboard

EN Selectively invalidates the cache based on what actually changed in Configuration.

Link copied to clipboard
private fun launchSaveCollector(target: CoroutineScope)
Link copied to clipboard
internal fun loadFromByteArray(data: ByteArray)
Link copied to clipboard
fun peek(key: Long): Float?

EN Reads a stored cache value without computing a fallback. Returns null on a miss.

Link copied to clipboard
private suspend fun performSave(context: Context)
Link copied to clipboard
fun removeResetListener(listener: () -> Unit)

EN Removes a previously registered reset listener. PT Remove um listener de reset previamente registrado.

Link copied to clipboard

EN Resets the diagnostic counters (hit, miss, eviction) to zero. PT Zera os contadores de diagnóstico (hit, miss, eviction).

Link copied to clipboard
Link copied to clipboard
Link copied to clipboard

EN Cancels the background persistence scope. Intended for test teardown. The scope is automatically re-created on next use (e.g. saveToPersistence).

Link copied to clipboard
Link copied to clipboard
private fun updateFactors(config: Configuration)